package com.sky.controller;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.LoginDTO;
import com.sky.dto.RegDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.LoginVO;
import com.sky.vo.RegVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户相关
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     * @param loginDTO
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    @CrossOrigin("http://localhost:5173")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        log.info("用户登录：{}", loginDTO);

        User user = userService.login(loginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        LoginVO loginVO = LoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .build();

        return Result.success(loginVO);
    }

    /**
     * 注册
     * @param regDTO
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/reg")
    @CrossOrigin("http://localhost:5173")
    public Result<RegVO> reg(@RequestBody RegDTO regDTO){
        RegVO regVO = userService.reg(regDTO);
        return Result.success(regVO);
    }

    /**
     * 用户信息
     * @return
     */
    @ApiOperation("用户信息")
    @GetMapping("/Info")
    @CrossOrigin("http://localhost:5173")
    public Result userInfo(){
        User user = userService.userInfo();
        return Result.success(user);
    }



    /**
     * 退出
     * @return
     */

//    @PostMapping("/logout")
//    @CrossOrigin("http://localhost:5173")
//    public Result<String> logout() {
//        return Result.success();
//    }

}
